﻿using System;
using System.Windows.Forms;
using YougeBookmark.Services;
using YougeBookmark.Utilities;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Data;

namespace YougeBookmark.UI
{
    public partial class QueryForm : Form
    {
        private readonly BookmarkManager _bookmarkManager;
        private readonly TagManager _tagManager;
        private readonly Logger _logger;
        private int _currentPage = 1;
        private TableLayoutPanel pnlSearch;
        private Label lblKeyword;
        private Label lblTags;
        private Label lblDate;
        private FlowLayoutPanel datePanel;
        private Label lblTo;
        private FlowLayoutPanel pagingPanel;
        private int _pageSize = 10;

        public QueryForm(BookmarkManager bookmarkManager, TagManager tagManager, Logger logger)
        {
            _bookmarkManager = bookmarkManager;
            _tagManager = tagManager;
            _logger = logger;

            InitializeComponent();
            InitializeGrid();
            LoadTags();
            PerformSearch();
        }

        //private void InitializeComponent()
        //{
        //    pnlSearch = new TableLayoutPanel();
        //    lblKeyword = new Label();
        //    txtKeyword = new TextBox();
        //    lblTags = new Label();
        //    clbTags = new CheckedListBox();
        //    lblDate = new Label();
        //    datePanel = new FlowLayoutPanel();
        //    dtpStart = new DateTimePicker();
        //    lblTo = new Label();
        //    dtpEnd = new DateTimePicker();
        //    btnSearch = new Button();
        //    pagingPanel = new FlowLayoutPanel();
        //    lblPageInfo = new Label();
        //    btnPrev = new Button();
        //    btnNext = new Button();
        //    dgvResults = new DataGridView();
        //    pnlSearch.SuspendLayout();
        //    datePanel.SuspendLayout();
        //    pagingPanel.SuspendLayout();
        //    ((System.ComponentModel.ISupportInitialize)dgvResults).BeginInit();
        //    SuspendLayout();
        //    // 
        //    // pnlSearch
        //    // 
        //    pnlSearch.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 65F));
        //    pnlSearch.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 40F));
        //    pnlSearch.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 181F));
        //    pnlSearch.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 60F));
        //    pnlSearch.Controls.Add(lblKeyword, 0, 0);
        //    pnlSearch.Controls.Add(txtKeyword, 1, 0);
        //    pnlSearch.Controls.Add(lblTags, 0, 1);
        //    pnlSearch.Controls.Add(clbTags, 1, 1);
        //    pnlSearch.Controls.Add(lblDate, 2, 0);
        //    pnlSearch.Controls.Add(datePanel, 3, 0);
        //    pnlSearch.Controls.Add(btnSearch, 2, 2);
        //    pnlSearch.Controls.Add(pagingPanel, 0, 2);
        //    pnlSearch.Location = new Point(30, 12);
        //    pnlSearch.Name = "pnlSearch";
        //    pnlSearch.RowStyles.Add(new RowStyle(SizeType.Absolute, 30F));
        //    pnlSearch.RowStyles.Add(new RowStyle(SizeType.Absolute, 70F));
        //    pnlSearch.RowStyles.Add(new RowStyle(SizeType.Absolute, 30F));
        //    pnlSearch.Size = new Size(592, 228);
        //    pnlSearch.TabIndex = 1;
        //    // 
        //    // lblKeyword
        //    // 
        //    lblKeyword.Location = new Point(3, 0);
        //    lblKeyword.Name = "lblKeyword";
        //    lblKeyword.Size = new Size(59, 23);
        //    lblKeyword.TabIndex = 0;
        //    // 
        //    // txtKeyword
        //    // 
        //    txtKeyword.Location = new Point(68, 3);
        //    txtKeyword.Name = "txtKeyword";
        //    txtKeyword.Size = new Size(18, 23);
        //    txtKeyword.TabIndex = 1;
        //    // 
        //    // lblTags
        //    // 
        //    lblTags.Location = new Point(3, 30);
        //    lblTags.Name = "lblTags";
        //    lblTags.Size = new Size(59, 23);
        //    lblTags.TabIndex = 2;
        //    // 
        //    // clbTags
        //    // 
        //    clbTags.BorderStyle = BorderStyle.FixedSingle;
        //    pnlSearch.SetColumnSpan(clbTags, 3);
        //    clbTags.Location = new Point(68, 33);
        //    clbTags.Name = "clbTags";
        //    clbTags.Size = new Size(120, 56);
        //    clbTags.TabIndex = 3;
        //    // 
        //    // lblDate
        //    // 
        //    lblDate.Location = new Point(206, 0);
        //    lblDate.Name = "lblDate";
        //    lblDate.Size = new Size(69, 23);
        //    lblDate.TabIndex = 4;
        //    // 
        //    // datePanel
        //    // 
        //    datePanel.Controls.Add(dtpStart);
        //    datePanel.Controls.Add(lblTo);
        //    datePanel.Controls.Add(dtpEnd);
        //    datePanel.Location = new Point(387, 3);
        //    datePanel.Name = "datePanel";
        //    datePanel.Size = new Size(30, 24);
        //    datePanel.TabIndex = 5;
        //    // 
        //    // dtpStart
        //    // 
        //    dtpStart.Location = new Point(3, 3);
        //    dtpStart.Name = "dtpStart";
        //    dtpStart.Size = new Size(200, 23);
        //    dtpStart.TabIndex = 0;
        //    // 
        //    // lblTo
        //    // 
        //    lblTo.Location = new Point(3, 29);
        //    lblTo.Name = "lblTo";
        //    lblTo.Size = new Size(100, 23);
        //    lblTo.TabIndex = 1;
        //    // 
        //    // dtpEnd
        //    // 
        //    dtpEnd.Location = new Point(3, 55);
        //    dtpEnd.Name = "dtpEnd";
        //    dtpEnd.Size = new Size(200, 23);
        //    dtpEnd.TabIndex = 2;
        //    // 
        //    // btnSearch
        //    // 
        //    pnlSearch.SetColumnSpan(btnSearch, 2);
        //    btnSearch.FlatAppearance.BorderColor = Color.FromArgb(25, 118, 210);
        //    btnSearch.FlatAppearance.MouseOverBackColor = Color.FromArgb(25, 118, 210);
        //    btnSearch.Location = new Point(206, 103);
        //    btnSearch.Name = "btnSearch";
        //    btnSearch.Size = new Size(75, 23);
        //    btnSearch.TabIndex = 6;
        //    // 
        //    // pagingPanel
        //    // 
        //    pnlSearch.SetColumnSpan(pagingPanel, 2);
        //    pagingPanel.Controls.Add(lblPageInfo);
        //    pagingPanel.Controls.Add(btnPrev);
        //    pagingPanel.Controls.Add(btnNext);
        //    pagingPanel.Location = new Point(3, 103);
        //    pagingPanel.Name = "pagingPanel";
        //    pagingPanel.Size = new Size(83, 24);
        //    pagingPanel.TabIndex = 7;
        //    // 
        //    // lblPageInfo
        //    // 
        //    lblPageInfo.Location = new Point(3, 0);
        //    lblPageInfo.Name = "lblPageInfo";
        //    lblPageInfo.Size = new Size(100, 23);
        //    lblPageInfo.TabIndex = 0;
        //    // 
        //    // btnPrev
        //    // 
        //    btnPrev.Location = new Point(3, 26);
        //    btnPrev.Name = "btnPrev";
        //    btnPrev.Size = new Size(75, 23);
        //    btnPrev.TabIndex = 1;
        //    // 
        //    // btnNext
        //    // 
        //    btnNext.Location = new Point(3, 55);
        //    btnNext.Name = "btnNext";
        //    btnNext.Size = new Size(75, 23);
        //    btnNext.TabIndex = 2;
        //    // 
        //    // dgvResults
        //    // 
        //    dgvResults.Location = new Point(71, 294);
        //    dgvResults.Name = "dgvResults";
        //    dgvResults.Size = new Size(240, 150);
        //    dgvResults.TabIndex = 0;
        //    // 
        //    // QueryForm
        //    // 
        //    ClientSize = new Size(800, 600);
        //    Controls.Add(dgvResults);
        //    Controls.Add(pnlSearch);
        //    Name = "QueryForm";
        //    Text = "书签查询";
        //    pnlSearch.ResumeLayout(false);
        //    pnlSearch.PerformLayout();
        //    datePanel.ResumeLayout(false);
        //    pagingPanel.ResumeLayout(false);
        //    ((System.ComponentModel.ISupportInitialize)dgvResults).EndInit();
        //    ResumeLayout(false);            
        //}       


        private void InitializeGrid()
        {
            dgvResults.Columns.Clear();
            dgvResults.AutoGenerateColumns = false;

            // 标题列
            dgvResults.Columns.Add(new DataGridViewTextBoxColumn
            {
                HeaderText = "标题",
                DataPropertyName = "Title",
                FillWeight = 50
            });

            // URL列
            dgvResults.Columns.Add(new DataGridViewLinkColumn
            {
                HeaderText = "URL",
                DataPropertyName = "Url",
                FillWeight = 40
            });

            // 创建时间列
            dgvResults.Columns.Add(new DataGridViewTextBoxColumn
            {
                HeaderText = "创建时间",
                DataPropertyName = "CreatedAt",
                FillWeight = 30,
                DefaultCellStyle = new DataGridViewCellStyle
                {
                    Format = "yyyy-MM-dd HH:mm"
                }
            });

            // 标签列（自定义显示）
            dgvResults.Columns.Add(new DataGridViewTextBoxColumn
            {
                HeaderText = "标签",
                FillWeight = 30,
                CellTemplate = new TagsCellTemplate(),
                DataPropertyName = "Tags"
            });

            dgvResults.Columns.Add(new DataGridViewTextBoxColumn
            {
                HeaderText = "摘要",
                DataPropertyName = "Summary",
                FillWeight = 50
            });

            dgvResults.Columns.Add(new DataGridViewImageColumn
            {
                HeaderText = "图片",       // 列标题
                DataPropertyName = "Img",  // 绑定的数据源字段名（例如存储byte[]或Image对象）
                ImageLayout = DataGridViewImageCellLayout.Zoom, // 图片缩放模式（Zoom=适应单元格）
                //Width = 1,                    // 列宽
                DefaultCellStyle = new DataGridViewCellStyle
                {
                    Padding = new Padding(0) // 移除单元格内边距
                }
            });

            dgvResults.Columns.Add(new DataGridViewTextBoxColumn
            {
                HeaderText = "备注",
                DataPropertyName = "Remark",
                FillWeight = 50
            });
        }

        private async void LoadTags()
        {
            try
            {
                var (tags, _) = await _tagManager.GetPagedTagsAsync(0, int.MaxValue);
                clbTags.Items.Clear();
                clbTags.Items.AddRange(tags.Select(t => t.Tag.Name).ToArray());
            }
            catch (Exception ex)
            {
                _logger.Error($"加载标签失败: {ex.Message}", ex);
            }
        }

        private async void PerformSearch()
        {
            try
            {
                var selectedTags = clbTags.CheckedItems.Cast<string>().ToList();
                var (items, total) = await _bookmarkManager.SearchBookmarksAsync(
                    keyword: txtKeyword.Text,
                    tags: selectedTags,
                    startDate: dtpStart.Value.Date,
                    endDate: dtpEnd.Value.Date.AddDays(1).AddSeconds(-1),
                    page: _currentPage,
                    pageSize: _pageSize
                );

                /*dgvResults.DataSource*/
                var lt = items.Select(b => new
                {
                    b.Id,
                    b.Title,
                    b.Url,
                    b.CreatedAt,
                    Tags = b.BookmarkTags.Select(bt => bt.Tag.Name),
                    b.Summary,
                    b.Remark,
                    b.ThumbnailPath,
                    Img = Tool.ConvertImageToByteArray("Resources/" + b.ThumbnailPath)
                }).ToList();

                dgvResults.DataSource = lt;

                UpdatePagingControls(total);
            }
            catch (Exception ex)
            {
                _logger.Error($"查询失败: {ex.Message}", ex);
                MessageBox.Show("查询失败: " + ex.Message);
            }
        }

        private void UpdatePagingControls(int total)
        {
            btnPrev.Enabled = _currentPage > 1;
            btnNext.Enabled = _currentPage * _pageSize < total;
            lblPageInfo.Text = $"第 {_currentPage} 页 / 共 {(int)Math.Ceiling(total / (double)_pageSize)} 页";
        }

        #region 事件处理
        private void BtnSearch_Click(object sender, EventArgs e)
        {
            _currentPage = 1;
            PerformSearch();
        }

        private void BtnPrev_Click(object sender, EventArgs e)
        {
            _currentPage--;
            PerformSearch();
        }

        private void BtnNext_Click(object sender, EventArgs e)
        {
            _currentPage++;
            PerformSearch();
        }
        #endregion

        #region 自定义单元格
        private class TagsCellTemplate : DataGridViewTextBoxCell
        {
            protected override void Paint(
                Graphics graphics,
                System.Drawing.Rectangle clipBounds,
                System.Drawing.Rectangle cellBounds,
                int rowIndex,
                DataGridViewElementStates cellState,
                object value,
                object formattedValue,
                string errorText,
                DataGridViewCellStyle cellStyle,
                DataGridViewAdvancedBorderStyle advancedBorderStyle,
                DataGridViewPaintParts paintParts)
            {
                base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,
                    value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);

                if (value is IEnumerable<string> tags)
                {
                    var text = string.Join(", ", tags);
                    TextRenderer.DrawText(
                        graphics,
                        text,
                        cellStyle.Font,
                        cellBounds,
                        cellStyle.ForeColor,
                        TextFormatFlags.VerticalCenter | TextFormatFlags.Left);
                }
            }
        }
        #endregion

        #region 控件声明
        private TextBox txtKeyword;
        private CheckedListBox clbTags;
        private DateTimePicker dtpStart;
        private DateTimePicker dtpEnd;
        private Button btnSearch;
        private DataGridView dgvResults;
        private Label lblPageInfo;
        private Button btnPrev;
        private Button btnNext;
        //private Panel pnlSearch;
        //private Label lblKeyword;
        //private Label lblTags;
        //private Label lblDate;
        #endregion 控件声明

        private void InitializeComponent()
        {
            // 基础布局配置
            this.SuspendLayout();
            this.ClientSize = new Size(800, 600);
            this.Text = "书签查询";
            this.FormBorderStyle = FormBorderStyle.Sizable;

            // 搜索条件面板
            var pnlSearch = new Panel
            {
                Dock = DockStyle.Top,
                Height = 120,
                BorderStyle = BorderStyle.FixedSingle
            };

            // 搜索关键词
            var lblKeyword = new Label { Text = "关键词:", Left = 10, Top = 10, AutoSize = true };
            this.txtKeyword = new TextBox { Left = 70, Top = 7, Width = 200 };

            // 标签选择
            var lblTags = new Label { Text = "标签:", Left = 10, Top = 40, AutoSize = true };
            this.clbTags = new CheckedListBox
            {
                Left = 70,
                Top = 37,
                Width = 200,
                Height = 60,
                CheckOnClick = true,
                //SelectionMode = SelectionMode.None
            };

            // 日期范围
            var lblDate = new Label { Text = "日期范围:", Left = 300, Top = 10, AutoSize = true };
            this.dtpStart = new DateTimePicker
            {
                Left = 370,
                Top = 7,
                Width = 120,
                Format = DateTimePickerFormat.Short
            };
            this.dtpEnd = new DateTimePicker
            {
                Left = 500,
                Top = 7,
                Width = 120,
                Format = DateTimePickerFormat.Short,
                Value = DateTime.Now
            };

            // 搜索按钮
            this.btnSearch = new Button
            {
                Text = "搜索",
                Left = 650,
                Top = 7,
                Width = 80,
                BackColor = SystemColors.ControlDark
            };
            this.btnSearch.Click += BtnSearch_Click;

            // 分页控件
            this.lblPageInfo = new Label { Left = 10, Top = 100, AutoSize = true };
            this.btnPrev = new Button { Text = "上一页", Left = 150, Top = 95, Enabled = false };
            this.btnNext = new Button { Text = "下一页", Left = 230, Top = 95, Enabled = false };
            this.btnPrev.Click += BtnPrev_Click;
            this.btnNext.Click += BtnNext_Click;

            // 结果表格
            this.dgvResults = new DataGridView
            {
                Dock = DockStyle.Fill,
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                ReadOnly = true,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
            };
            // 自动调整列宽
            //dgvResults.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            // 自动调整行高
            //dgvResults.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

            dgvResults.CellContentClick += DgvResults_CellContentClick;

            // 订阅 CellFormatting 事件
            //dgvResults.CellFormatting += (sender, e) =>
            //{
            //    if (dgvResults.Columns[e.ColumnIndex] is DataGridViewImageColumn && e.RowIndex >= 0)
            //    {
            //        // 获取原始图片
            //        var cell = dgvResults.Rows[e.RowIndex].Cells[e.ColumnIndex];
            //        Image originalImage = cell.Value as Image;

            //        if (originalImage != null)
            //        {
            //            // 根据单元格尺寸生成缩略图
            //            int targetWidth = cell.Size.Width;
            //            int targetHeight = cell.Size.Height;

            //            // 创建缩略图（保持比例）
            //            using (var thumbnail = originalImage.GetThumbnailImage(
            //                targetWidth,
            //                targetHeight,
            //                () => false, // 不需要回调
            //                IntPtr.Zero))
            //            {
            //                e.Value = thumbnail;
            //            }
            //        }
            //    }
            //};

            // 控件组合 
            pnlSearch.Controls.AddRange(new Control[]
            {
        lblKeyword, txtKeyword,
        lblTags, clbTags,
        lblDate, dtpStart, dtpEnd,
        btnSearch,
        lblPageInfo, btnPrev, btnNext
            });
            this.Controls.Add(dgvResults);
            this.Controls.Add(pnlSearch);
            this.ResumeLayout(false);
        }

        // 事件处理方法
        private void DgvResults_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 确保点击的是链接列且行索引有效（避免点击标题行）
            if (e.RowIndex >= 0 && dgvResults.Columns[e.ColumnIndex] is DataGridViewLinkColumn)
            {
                // 获取点击的 URL 值
                var url = dgvResults.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString();

                if (!string.IsNullOrEmpty(url))
                {
                    // 用默认浏览器打开链接
                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = url,
                        UseShellExecute = true
                    });
                }
            }
            if (e.RowIndex >= 0 && dgvResults.Columns[e.ColumnIndex] is DataGridViewImageColumn)
            {
                var va = dgvResults.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                if (va is byte[])
                {
                    var bts = (va as byte[]);
                    var img = bts.BytesToImage();
                    var pic = new PictureBox();
                    pic.Image = img;
                    pic.SizeMode = PictureBoxSizeMode.AutoSize;
                    pic.Parent = this;
                    pic.Location = new Point((this.Width - pic.Width) / 2, (this.Height - pic.Height) / 2);
                    pic.BringToFront();
                    pic.Show();
                    pic.Click += ((s, e) =>
                    {
                        pic.Hide();
                        pic.Dispose();
                    });
                }
            }

        }

    }
}